package com.om.abom.config;

import com.om.abom.utils.PsInfoSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
@Slf4j
public class WebSocketHandler extends TextWebSocketHandler
{
    @Autowired
    private PsInfoSender psInfoSender;

    @Override
    public void afterConnectionEstablished(WebSocketSession socketSession)
    {
        log.info("WebSocket连接已建立");

        psInfoSender.sendAllHostPsInfo(socketSession);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception
    {
        // 处理接收到的文本消息
        String receivedMessage = message.getPayload(); // 获取接收到的消息内容
        log.info("接收到的消息：{}", receivedMessage); // 打印接收到的消息内容

        // 回复消息
        String replyMessage = "服务器收到了您的消息：" + receivedMessage; // 构造回复消息内容
        session.sendMessage(new TextMessage(replyMessage)); // 发送回复消息给客户端
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
    {
        // 处理连接关闭后的逻辑
        log.info("WebSocket连接已关闭"); // 打印日志信息，表示WebSocket连接已关闭
    }
}
